package com.zzj.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zzj.annotation.LogAnnotation;
import com.zzj.base.Result;
import com.zzj.entity.Category;
import com.zzj.model.dto.CategoryCreateDto;
import com.zzj.model.dto.QueryListDto;
import com.zzj.service.ICategoryService;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 分类表 前端控制器
 * </p>
 *
 * @author zzj
 * @since 2023-07-17
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Resource
    private ICategoryService categoryService;

    @LogAnnotation(name = "创建分类", description = "传入类名创建分类")
    @PostMapping("create")
    public Result create(@RequestBody @Validated CategoryCreateDto in) {
        Category category = categoryService.findCategory(in.getName());
        if (category != null) {
            return Result.error("分类已存在");
        }
        Category create = categoryService.create(in);
        return Result.success(create);
    }

    @LogAnnotation(name = "查询分类", description = "分页获取分类列表")
    @PostMapping("queryList")
    public Result queryList(@RequestBody @Validated QueryListDto in) {
        IPage<Category> categoryIPage = categoryService.queryList(in);
        return Result.success(categoryIPage);
    }

    @LogAnnotation(name = "删除分类", description = "根据分类ID删除")
    @PostMapping("remove")
    public Result remove(@RequestParam(value = "id") int id) {
        boolean b = categoryService.removeById(id);
        if (!b) {
            return Result.error("删除失败");
        }
        return Result.success("删除成功");
    }
}
